package com.jy.novel.interceptor;

import com.jy.novel.common.Fields;
import com.jy.novel.pojo.system.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by jihb on 4/12/16.
 * 登录拦截
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    public LoginInterceptor() {
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object object = session.getAttribute(Fields.LOGIN_USER_INFO);
        if (object == null || !(object instanceof UserInfo)){
            if (isAjax(request)){
                response.addHeader("needLogin","true");
                this.writeBody(response,"请先登录");
            }else {
                response.setContentType("text/html;charset=utf-8");
                StringBuilder sb = new StringBuilder();
                sb.append("<!DOCTYPE html><html><head lang=\"en\"><meta charset=\"UTF-8\"><title>${SystemCfg.systemName}</title>");
                sb.append("<script type=\"text/javascript\">parent.window.location.href=\"" + request.getContextPath() + "/login\"</script>");
                sb.append("</head><body></body></html>");
                this.writeBody(response, sb.toString());
            }
            return false;
        }
        return true;
    }

    private void writeBody(HttpServletResponse response,String body){
        try {
            response.getWriter().write(body);
        } catch (IOException e) {
            logger.error("writeBody error",e.getMessage());
        }
    }

    private boolean isAjax(HttpServletRequest request){
        return request.getHeader("x-requested-with") != null && "XMLHttpRequest".equals(request.getHeader("x-requested-with").toString());
    }
}
